﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRM_SharePoint_Transports
{
    public class SharePointListSendTransport : BlueIntegrator.Extensibility.SendTransportBase
    {
        public override void Initialise(string portId, string transportName, System.Collections.IDictionary transportParameters)
        {
            m_portId = portId;
            m_dal = transportParameters["__DAL"] as BlueIntegrator.DAL.DALBase;
            m_spcf = transportParameters["__RPCF"] as BlueIntegrator.Messaging.SendPortConfigurationForm;
            m_properties = new System.Collections.Hashtable();

            foreach (System.Collections.DictionaryEntry dent in transportParameters)
            {
                m_properties[dent.Key] = BlueIntegrator.Messaging.SettingTokenHelper.ResolveTokens(m_dal, BlueIntegrator.Helpers.Conversion.SafeGetString(dent.Value));
            }

            m_api = new SSISLib.SharePointListAPI();
        }

        public override System.IO.Stream SendMessage(System.IO.Stream messageContents, System.Collections.IDictionary contextParameters)
        {
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            BlueIntegrator.Helpers.StreamReader.LoadXmlDoc(xmlDoc, messageContents);

            // Copy properties for token replacement
            System.Collections.Hashtable props = new System.Collections.Hashtable();

            foreach (System.Collections.DictionaryEntry dent in m_properties)
            {
                string val = BlueIntegrator.Helpers.Conversion.SafeGetString(dent.Value);

                if (val.Contains("%"))
                {
                    foreach (System.Collections.DictionaryEntry dent2 in contextParameters)
                    {
                        val = val.Replace("%" + dent2.Key + "%", BlueIntegrator.Helpers.Conversion.SafeGetString(dent2.Value));
                    }
                }

                props[dent.Key] = val;
            }

            m_api.WriteData(props, xmlDoc, m_dal);
            return null;
        }

        public override System.Windows.Forms.Control[] GetTabPages()
        {
            return new System.Windows.Forms.Control[] {new SharePointListTransportConfigControl(true, null, m_spcf)};
        }

        System.Collections.Hashtable m_properties = new System.Collections.Hashtable();
        string m_portId;
        BlueIntegrator.DAL.DALBase m_dal;
        SSISLib.SharePointListAPI m_api;
        BlueIntegrator.Messaging.SendPortConfigurationForm m_spcf;
    }
}
